package niotest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

public class NIOStudy {
	private static Selector selector;

	public static void main(String[] args) throws Exception {
		selector = SelectorProvider.provider().openSelector();
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.configureBlocking(false);
		InetSocketAddress address = new InetSocketAddress(6789);
		ssc.socket().bind(address);
		ssc.register(selector, SelectionKey.OP_ACCEPT);

		int select = 0;
		while ((select = selector.select()) > 0) {
			System.out.println("select :" + select);
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Set<SelectionKey> allKeys = selector.keys();
			System.out.println(selectedKeys);
			System.out.println(allKeys);
			for (Iterator<SelectionKey> i = selectedKeys.iterator(); i
					.hasNext();) {
				SelectionKey key = i.next();
				i.remove();
				System.out.println(key);
				if (key.isAcceptable()) {
					accept(key);
				}
				if (key.isReadable()) {
					read(key);
				}
				if (key.isWritable()) {
					write(key);
				}
				if (key.isConnectable()) {
					connect(key);
				}
			}
			System.out.println(selectedKeys);
			System.out.println(allKeys);
		}
	}

	private static void connect(SelectionKey key) throws Exception  {
		System.out.println("connect");

	}

	private static void write(SelectionKey key) throws Exception  {
		System.out.println("write");

	}

	private static void read(SelectionKey key) throws Exception  {
		System.out.println("read");
		SocketChannel sc =(SocketChannel)key.channel();
		ByteBuffer bb = ByteBuffer.allocateDirect(1024);
		sc.read(bb);
		bb.flip();
		System.out.println(bb.asCharBuffer());
	}

	private static void accept(SelectionKey key) throws Exception {
		System.out.println("accept");
		ServerSocketChannel ssc =(ServerSocketChannel)key.channel();
		SocketChannel sc = ssc.accept();
		sc.configureBlocking(false);
		sc.register(selector, SelectionKey.OP_READ);
	}
}
